using RadioTimer.ViewModels;
using System.ComponentModel;

namespace RadioTimer.Views
{
    /// <summary>
    /// 主页面的代码后置类
    /// 继承自ContentPage，作为语音报时App的主页面
    /// 展示报时统计信息、服务控制和状态显示
    /// 通过数据绑定与MainPageViewModel进行交互
    /// </summary>
    public partial class HomePage : ContentPage
    {
        private bool _isPressed = false;
        private bool _isAnimating = false;
        private CancellationTokenSource _animationCancellationTokenSource = new CancellationTokenSource();
        private Color _lastButtonColor = Colors.Transparent;
        
        /// <summary>
        /// 初始化HomePage实例
        /// 通过依赖注入获取ViewModel实例，并设置为数据绑定上下文
        /// </summary>
        /// <param name="viewModel">首页的视图模型实例</param>
        public HomePage(MainPageViewModel viewModel)
        {
            InitializeComponent();
            BindingContext = viewModel;
            
            // 订阅页面生命周期事件
            this.Appearing += OnPageAppearing;
            this.Disappearing += OnPageDisappearing;
            
            // 订阅按钮点击事件
            MainButton.Pressed += OnButtonPressed;
            MainButton.Released += OnButtonReleased;
            
            // 订阅ViewModel属性变化事件，用于颜色变化动画
            if (viewModel is INotifyPropertyChanged notifyPropertyChanged)
            {
                notifyPropertyChanged.PropertyChanged += OnViewModelPropertyChanged;
            }
        }
        
        /// <summary>
        /// ViewModel属性变化事件处理
        /// </summary>
        private async void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(MainPageViewModel.ServiceButtonColor))
            {
                // 当按钮颜色属性变化时，执行颜色变化动画
                if (BindingContext is MainPageViewModel viewModel)
                {
                    var newColor = viewModel.ServiceButtonColor;
                    if (_lastButtonColor != Colors.Transparent && _lastButtonColor != newColor)
                    {
                        await AnimateButtonColorChange();
                    }
                    _lastButtonColor = newColor;
                }
            }
        }
        
        /// <summary>
        /// 执行按钮颜色变化动画
        /// </summary>
        private async Task AnimateButtonColorChange()
        {
            try
            {
                // 更明显的颜色变化动画效果
                await ButtonBackground.ScaleTo(1.1, 100, Easing.SinInOut);
                await ButtonBackground.FadeTo(0.7, 100, Easing.SinInOut);
                await ButtonBackground.ScaleTo(1.0, 100, Easing.SinInOut);
                await ButtonBackground.FadeTo(1.0, 100, Easing.SinInOut);
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"颜色变化动画执行出错: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 页面出现时启动动画
        /// </summary>
        private void OnPageAppearing(object sender, EventArgs e)
        {
            StartPulseAnimation();
            
            // 初始化按钮颜色
            if (BindingContext is MainPageViewModel viewModel)
            {
                _lastButtonColor = viewModel.ServiceButtonColor;
            }
        }
        
        /// <summary>
        /// 页面消失时停止动画
        /// </summary>
        private void OnPageDisappearing(object sender, EventArgs e)
        {
            if (!_isAnimating) return;
            StopPulseAnimation();
        }
        
        /// <summary>
        /// 启动脉冲动画
        /// </summary>
        private void StartPulseAnimation()
        {
            if (_isAnimating) return;
            
            _isAnimating = true;
            _animationCancellationTokenSource = new CancellationTokenSource();
            
            // 创建脉冲动画
            AnimatePulses();
        }
        
        /// <summary>
        /// 停止脉冲动画
        /// </summary>
        private void StopPulseAnimation()
        {
            _isAnimating = false;
            _animationCancellationTokenSource.Cancel();
        }
        
        /// <summary>
        /// 执行脉冲动画
        /// </summary>
        private async void AnimatePulses()
        {
            try
            {
                while (_isAnimating && !_animationCancellationTokenSource.Token.IsCancellationRequested)
                {
                    // 重置脉冲大小和透明度
                    Pulse1.Scale = 1;
                    Pulse1.Opacity = 0.3;
                    Pulse2.Scale = 1;
                    Pulse2.Opacity = 0.2;
                    Pulse3.Scale = 1;
                    Pulse3.Opacity = 0.1;
                    
                    // 动画第1个脉冲
                    var pulse1Scale = Pulse1.RelScaleTo(1.5, 1500, Easing.SinInOut);
                    var pulse1Fade = Pulse1.FadeTo(0, 1500, Easing.SinInOut);
                    await Task.WhenAll(pulse1Scale, pulse1Fade);
                    
                    if (!_isAnimating || _animationCancellationTokenSource.Token.IsCancellationRequested) break;
                    
                    // 动画第2个脉冲
                    var pulse2Scale = Pulse2.RelScaleTo(1.5, 1500, Easing.SinInOut);
                    var pulse2Fade = Pulse2.FadeTo(0, 1500, Easing.SinInOut);
                    await Task.WhenAll(pulse2Scale, pulse2Fade);
                    
                    if (!_isAnimating || _animationCancellationTokenSource.Token.IsCancellationRequested) break;
                    
                    // 动画第3个脉冲
                    var pulse3Scale = Pulse3.RelScaleTo(1.5, 1500, Easing.SinInOut);
                    var pulse3Fade = Pulse3.FadeTo(0, 1500, Easing.SinInOut);
                    await Task.WhenAll(pulse3Scale, pulse3Fade);
                    
                    if (!_isAnimating || _animationCancellationTokenSource.Token.IsCancellationRequested) break;
                    
                    // 等待一小段时间再开始下一轮动画
                    await Task.Delay(500, _animationCancellationTokenSource.Token);
                }
            }
            catch (OperationCanceledException)
            {
                // 动画被取消，正常情况
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"动画执行出错: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 按钮按下时的动画效果
        /// </summary>
        private async void OnButtonPressed(object sender, EventArgs e)
        {
            if (_isPressed) return;
            _isPressed = true;
            
            // 创建按下动画
            var scaleAnimation = ButtonBackground.ScaleTo(0.9, 100, Easing.SinInOut);
            var highlightAnimation = GlassHighlight.FadeTo(0.2, 100, Easing.SinInOut);
            
            await Task.WhenAll(scaleAnimation, highlightAnimation);
        }
        
        /// <summary>
        /// 按钮释放时的动画效果
        /// </summary>
        private async void OnButtonReleased(object sender, EventArgs e)
        {
            if (!_isPressed) return;
            _isPressed = false;
            
            // 创建释放动画
            var scaleAnimation = ButtonBackground.ScaleTo(1, 100, Easing.SinInOut);
            var highlightAnimation = GlassHighlight.FadeTo(0.4, 100, Easing.SinInOut);
            
            await Task.WhenAll(scaleAnimation, highlightAnimation);
        }
        
        /// <summary>
        /// 清理资源
        /// </summary>
        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            
            // 取消订阅事件
            if (BindingContext is INotifyPropertyChanged notifyPropertyChanged)
            {
                notifyPropertyChanged.PropertyChanged -= OnViewModelPropertyChanged;
            }
            
            StopPulseAnimation();
            _animationCancellationTokenSource?.Dispose();
        }
    }
}